<?php
/* @var $this PhancongController */
/* @var $model Phancong */

$this->breadcrumbs=array(
	'Phân công giảng dạy',
);

$this->menu=array(
	array('label'=>'Phân công giảng dạy','url'=>array('admin')),
	array('label'=>'Xem phân công','url'=>array('xemphancong')),
	array('label'=>'Phân công công tác khác','url'=>array('pccongtackhac/admin')),
	array('label'=>'Quản lý công tác khác','url'=>array('congtackhac/admin')),
	//array('label'=>'Quản lý thời khóa biểu','url'=>array('upload/admin')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#phancong-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");

$toggleUDetails = <<<JS
 $('body').on('click','a.toggle',function(e){
    e.preventDefault();

    if(this.href.split('#')[1]=='loaded') return $(this).closest("tr").next('tr.toggle').toggle();

    trow=$(this).closest("tr");

   var ajaxOpts={type:"POST", url:this.href ,dataType:'json',success:function(data){
            $(trow).after(data.row);
      }
    };

   this.href=this.href+'#loaded';

   $.ajax(ajaxOpts);

  });
JS;
Yii::app()->clientScript->registerScript('toggleUD', $toggleUDetails, CClientScript::POS_READY);

?>

<h1>Phân công giảng dạy</h1>

<p><?php echo CHtml::link('Bộ lọc tìm kiếm','#',array('class'=>'search-button')); ?></p>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>
</div><!-- search-form -->

<?php $connection=Yii::app()->db;   // assuming you have configured a "db" connection
		$command=$connection->createCommand()
		->select('magv,tengv')
		->from('giangvien')
		->query();
		$giangvien= array();
		$giangvien['rong']='';
		foreach($command as $row)
		{
			//array_push($ngach,$row);
			$giangvien[$row['magv']]=$row['tengv'];
		}


$this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'phancong-grid',
	'dataProvider'=>$model->search(),
	//'filter'=>$model,
	'columns'=>array(
		/*array(
            'name'=>'nhomlop.makhoilop',
        ),*/
		array(
			'name'=>'monhoc.tenmh',
			//'filter'=>CHtml::activeTextField($model,'monhoc_search'),
			//'filter'=>CHtml::dropDownList("Phancong[monhoc.tenmh]",$model->monhoc->tenmh, CHtml::listData(monhoc::model()->findAll(),"mamh", "tenmh")),
		),
		array(
            'header' => 'Nhóm lớp',
            'name'=>'maNhom',
			'value'=>function($model){
				return substr($model->maNhom,21);
			},
        ),
		array(
			'header'=>'Tổng tiết',
			'value'=>function($model){ 
			$connection=Yii::app()->db;   // assuming you have configured a "db" connection
			$command=$connection->createCommand()
			->select('(monhoc.sotietLT+monhoc.sotietTH)')
			->from('nhomlop, monhoc, phancong')
			->where('nhomlop.mamh=monhoc.mamh AND nhomlop.maNhom=phancong.maNhom AND phancong.maNhom="'.$model->maNhom.'"')
			->queryRow();
			return $command['(monhoc.sotietLT+monhoc.sotietTH)']*1;
			},
		),
		array(
            'header' => 'Giảng viên',
            'value' => 	//'CHtml::textField("Phancong[magvchinh]",$data->magvchinh)',
			function($model){
				return CHtml::dropDownList("Phancong[magvchinh]",$model->magvchinh, CHtml::listData(giangvien::model()->findAll(),"magv", "tengv"), array("empty"=>""));
			}
						,
            'type' => 'raw',
        ),
		array(
			'header'=>'Số tiết',
			'value'=> 'CHtml::textField("Phancong[sotietgvchinh]",$data->sotietgvchinh,array("class"=>"sotietchange"))',
			'type'=>'raw',
		),
		array(
            'header' => 'Trợ giảng',
            'value' => 
			function($model){
				return CHtml::dropDownList("Phancong[magvphu]",$model->magvphu, CHtml::listData(giangvien::model()->findAll(),"magv", "tengv"), array("empty"=>"",));
			}
			,
            'type' => 'raw',
        ),
		array(
			'header'=>'Số tiết',
			'value'=> 'CHtml::textField("Phancong[sotietgvphu]",$data->sotietgvphu,array("readonly"=>"readonly"))',
			'type'=>'raw',
		),
		array(
            'class' => 'CButtonColumn',
            'template' => '{view}{update}',
            'buttons' => array(
				'view'=>array(
					'label'=>'Xem chi tiết',
					'url'=>'Yii::app()->controller->createUrl("xemChiTiet", array("id"=>$data->maNhom))',
					'options'=>array('class'=>'toggle',),
				),
                'update' => array(
                    'options' => array('class' => 'save-ajax-button'),
                    'url' => 'Yii::app()->controller->createUrl("saveModel", array("id"=>$data->maNhom))',
                ),
            ),
        ),
	),
)); ?>
	<?php echo CHtml::submitButton('Lưu', array('id'=>'btnLuu')); ?>

	<script type="text/javascript">
$(function(){
	$('#phancong-grid').on('change','input.sotietchange',function(){
		var rowt=$(this).parent().parent();
		var sotietgvchinh=$(this).val();
		var sotietgvphu=rowt.children(':nth-child(7)').children(':text').val();
		var tongtiet=rowt.children(':nth-child(3)').text();
		//alert(dt1);
		if(sotietgvchinh>tongtiet)
		{
			alert('Số tiết phải nhỏ hơn tổng tiết!');
			$(this).val(tongtiet);
			rowt.children(':nth-child(7)').children(':text').val(0);
		}
		else{
			rowt.children(':nth-child(7)').children(':text').val(tongtiet-sotietgvchinh);
		}
	});
	$('#btnLuu').click(function() {
		$('#phancong-grid a.save-ajax-button').each(function() {
			$(this).click();
		});
		alert('Đã lưu');
	});
    $('#phancong-grid').on('click','a.save-ajax-button',function(e)
    {
        var row = $(this).parent().parent();
 
        var data = $('select,input', row).serializeObject();
		//var data2 = $('text', row).serializeObject();
        $.ajax({
            type: 'POST',
            data: data,
            url: jQuery(this).attr('href'),
            success: function(data, textStatus, jqXHR) {
            },
            error: function(textStatus, errorThrown) {
				alert('Lỗi trong quá trình lưu!');
            }
        });
        return false;
    });
 
 
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
		
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
			
			//alert(o[this.name]);
        });
        return o;
};
});
</script>